package com.maoning.common.valid;

import javax.validation.Constraint;
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.lang.annotation.Annotation;
import java.util.HashSet;
import java.util.Set;

/**
 * @Author : 猫宁
 * @Date: 2021/10/8
 */
//自定义校验器(校验逻辑),范型的内容点进去查看,第一个泛型是校验的注解,第二个是校验的类型
public class ListValueConstraintValidator implements ConstraintValidator<ListValue,Integer> {

    private Set<Integer> set = new HashSet<>();
    @Override
    public void initialize(ListValue constraintAnnotation) {
        //可以从这里调用方法获取注解上的值,我们可以搞一个set集合,遍历他把他存起来,然后用来做接下来的逻辑判断
        final int[] vals = constraintAnnotation.vals();
        for (int val : vals) {
            set.add(val);
        }
        ConstraintValidator.super.initialize(constraintAnnotation);
    }

    @Override
    public boolean isValid(Integer integer, ConstraintValidatorContext constraintValidatorContext) {

        return set.contains(integer);
    }
}
